<?php

class Marjory_Service_ResponseWriter_DojoData implements Marjory_Service_ResponseWriter_Interface {
    protected $results;
    protected $fieldsToInclude = array();
    protected static $labelField = false;
    
    /**
     * @param array $fieldNames Array of fields to include in the response
     */
    public function includeFields(Array $fieldNames)
    {
        $this->fieldsToInclude = $fieldNames;
    }
    
    /**
     * @param array $results Array of Marjory_Document objects
     */
    public function setResponse(Marjory_Service_ResultProxy $results)
    {
        $this->results = $results;
    }
    
    public function getResponseObject()
    {
        $data = new Zend_Dojo_Data();
        $data->setIdentifier('uri');
        $data->setMetaData('numFound', $this->results->numResults);
        if (self::$labelField) {
            $data->setLabel(self::$labelField);
        }

        foreach($this->results as $key => $doc) {
            Marjory_Service::getLog()->log("Iterating over result $key ...", Zend_Log::DEBUG);
            /* @var $doc Marjory_Document */
            $item = array();
            foreach($doc->getFieldNames() as $fieldName) {
                if (empty($this->fieldsToInclude) || in_array($fieldName, $this->fieldsToInclude)) {
                    $item[$fieldName] = $doc->getField($fieldName);
                }
            }
            $item['_score'] = $doc->getScore();
            $item['uri']    = $doc->getURI();
            $data->addItem($item);
        }
        
        return $data;
    }
    
    /**
     * Returns the response string in the desired format
     * @return string
     */
    public function __toString()
    {
        return $this->getResponseObject()->toJson();
    }
}
